package com.yanqu.road.server.manger.specialtombrob;

import com.yanqu.road.entity.activity.ActivityConfig;
import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.activity.specialtombrob.config.sign.ActivitySignConfig;
import com.yanqu.road.entity.config.goods.GoodsInfo;
import com.yanqu.road.entity.enums.eActivityType;
import com.yanqu.road.entity.enums.eGamePlayerEventType;
import com.yanqu.road.entity.enums.eLogMoneyType;
import com.yanqu.road.entity.enums.eMailType;
import com.yanqu.road.entity.log.specialtombrob.LogSpecialTombRobSevenDaySign;
import com.yanqu.road.pb.specialtombrob.SpecialTombRobProto;
import com.yanqu.road.server.TempMgr;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.activity.ActivityModule;
import com.yanqu.road.server.gameplayer.module.activity.advertisement.AdvertisementActivityModule;
import com.yanqu.road.server.gameplayer.module.patrons.PatronsModule;
import com.yanqu.road.server.gameplayer.module.player.CurrencyModule;
import com.yanqu.road.server.logic.activity.BaseActivityData;
import com.yanqu.road.server.logic.activity.condition.BaseActivityCondition;
import com.yanqu.road.server.logic.mail.MailManager;
import com.yanqu.road.server.manger.MultipleLanguageMgr;
import com.yanqu.road.server.manger.ServerLanguageMgr;
import com.yanqu.road.server.manger.activity.NormalActivityMgr;
import com.yanqu.road.server.manger.config.GoodsMgr;
import com.yanqu.road.server.manger.log.AutoLogMgr;
import com.yanqu.road.server.protocol.ClientProtocol;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.utils.date.DateHelper;
import com.yanqu.road.utils.property.Property;
import com.yanqu.road.utils.property.PropertyHelper;
import com.yanqu.road.utils.string.StringUtils;

import java.math.BigInteger;
import java.text.MessageFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ActivityDaySignMgr extends TempMgr {
    private static Map<Integer, ActivitySignConfig> configMap = new HashMap<>();

    @Override
    public boolean init() throws Exception {
        return true;
    }

    @Override
    public boolean reloadConfig() throws Exception {
        return true;
    }

    @Override
    public boolean reloadData() throws Exception {
        return true;
    }

    @Override
    public boolean stop() {
        return true;
    }

    public static void reloadActivityData() {
        getLogger().info("reload ActivitySignMgr start");
        List<ActivityInfo> openActivityInfoList = NormalActivityMgr.getOpenActivityInfoList(eActivityType.DaySign.getValue());
        Map<Integer, ActivitySignConfig> tempConfigMap = new HashMap<>();
        for (ActivityInfo tmpActivityInfo : openActivityInfoList) {
            Map<String, ActivityConfig> activityConfigMap = NormalActivityMgr.getActivityConfigMap(tmpActivityInfo.getActivityId());
            ActivitySignConfig activitySignConfig = new ActivitySignConfig(tmpActivityInfo, activityConfigMap);
            tempConfigMap.put(activitySignConfig.getActivityId(), activitySignConfig);

            getLogger().info("reload ActivitySignMgr finish, activityId = {}", tmpActivityInfo.getActivityId());
        }
        //活动配置
        configMap = tempConfigMap;
        getLogger().info("reload ActivitySignMgr end.");
    }

    public static ActivitySignConfig getConfig(int activityId) {
        return configMap.get(activityId);
    }


    public static int simpleSign(GamePlayer player, int activityId, int conditionId) {
        ActivitySignConfig config = getConfig(activityId);
        if (config == null) {
            return GameErrorCode.E_ACTIVITY_NOT_OPEN;
        }
        int calc2DateTDOADays = DateHelper.calc2DateTDOADays(new Date(config.getActivityInfo().getBeginTime() * 1000), new Date());

        //拿出condition
        BaseActivityData baseActivityData = player.getModule(ActivityModule.class).getBaseActivityData(config.getActivityId());
        if (baseActivityData == null) {
            return GameErrorCode.E_SPECIAL_TOMB_ROB_SIGN_CONDITION_NO_EXIST;
        }
        BaseActivityCondition activityCondition = baseActivityData.getBaseActivityCondition(conditionId);
        if (activityCondition == null) {
            return GameErrorCode.E_SPECIAL_TOMB_ROB_SIGN_CONDITION_NO_EXIST;
        }
        int checkCondition = checkCondition(activityCondition, calc2DateTDOADays);
        if (checkCondition != 0) {
            return checkCondition;
        }

        //加奖励
        String reward = addAndGetCondition(player, activityCondition, config);

        SpecialTombRobProto.SpecialTombRobSevenDaySignResp.Builder builder = SpecialTombRobProto.SpecialTombRobSevenDaySignResp.newBuilder();
        builder.setRet(0);
        builder.setReward(reward);
        player.sendPacket(ClientProtocol.U_SPECIAL_TOMB_ROB_SIGN, builder);
        LogSpecialTombRobSevenDaySign logSpecialTombRobSevenDaySign = new LogSpecialTombRobSevenDaySign(activityId, player.getUserId(), calc2DateTDOADays, calc2DateTDOADays, reward, 0, new Date());
        AutoLogMgr.add(logSpecialTombRobSevenDaySign);

        //广告
        player.getModule(AdvertisementActivityModule.class).touchSevenSignAd();
        return 0;

    }

    public static int signPastDay(GamePlayer gamePlayer, int activityId, int conditionId, int day) {
        ActivitySignConfig config = getConfig(activityId);
        if (config == null) {
            return GameErrorCode.E_ACTIVITY_NOT_OPEN;
        }
        int calc2DateTDOADays = DateHelper.calc2DateTDOADays(new Date(config.getActivityInfo().getBeginTime() * 1000), new Date());
        if (calc2DateTDOADays < 0) {
            return GameErrorCode.E_ACTIVITY_OVER_TIME;
        }

        //拿出condition
        BaseActivityData baseActivityData = gamePlayer.getModule(ActivityModule.class).getBaseActivityData(config.getActivityId());
        if (baseActivityData == null) {
            return GameErrorCode.E_SPECIAL_TOMB_ROB_SIGN_CONDITION_NO_EXIST;
        }
        BaseActivityCondition activityCondition = baseActivityData.getBaseActivityCondition(conditionId);
        if (activityCondition == null) {
            return GameErrorCode.E_SPECIAL_TOMB_ROB_SIGN_CONDITION_NO_EXIST;
        }
        if (day >= calc2DateTDOADays) {
            return GameErrorCode.E_SPECIAL_TOMB_ROB_SIGN_CONDITION_ERROR;
        }
        //检查condition是否正常
        int checkCondition = checkCondition(activityCondition, day);
        if (checkCondition != 0) {
            return checkCondition;
        }
        //检测道具
        CurrencyModule module = gamePlayer.getModule(CurrencyModule.class);
        if (!module.currencyIsEnough(config.getProperty())) {
            return GameErrorCode.E_SPECIAL_TOMB_ROB_RE_SIGN_ITEM_NO_ENOUGH;
        }

        //口道具
        module.removeCurrency(config.getProperty(), eLogMoneyType.SpecialTombRobSign, eLogMoneyType.SpecialTombRobSignReSignCost);
        //加奖励
        String reward = addAndGetCondition(gamePlayer, activityCondition, config);

        SpecialTombRobProto.SpecialTombRobSevenDaySignAgainResp.Builder builder = SpecialTombRobProto.SpecialTombRobSevenDaySignAgainResp.newBuilder();
        builder.setRet(0);
        builder.setReward(reward);
        gamePlayer.sendPacket(ClientProtocol.U_SPECIAL_TOMB_ROB_SIGN_PAST_DAY, builder);
        LogSpecialTombRobSevenDaySign logSpecialTombRobSevenDaySign = new LogSpecialTombRobSevenDaySign(activityId, gamePlayer.getUserId(), day, calc2DateTDOADays, reward, 1, new Date());
        AutoLogMgr.add(logSpecialTombRobSevenDaySign);

        return 0;
    }

    public static int checkCondition(BaseActivityCondition activityCondition, int day) {

        if (activityCondition.getConditionType() != eGamePlayerEventType.SpecialTombRobSevenDaySign.getValue()) {
            return GameErrorCode.E_SPECIAL_TOMB_ROB_SIGN_CONDITION_ERROR;
        }

        if (activityCondition.isGetReward()) {               //已经领奖
            return GameErrorCode.E_SPECIAL_TOMB_ROB_SIGN_CONDITION_HAS_GET_REWARD;
        }

        if (activityCondition.getActivityConditionInfo().getParamList().get(2).intValue() != day) {
            return GameErrorCode.E_SPECIAL_TOMB_ROB_SIGN_CONDITION_DAY_ERROR;
        }

        return 0;
    }

    public static String addAndGetCondition(GamePlayer gamePlayer, BaseActivityCondition activityCondition, ActivitySignConfig config) {
        activityCondition.setValue(BigInteger.ONE);
        String reward = activityCondition.getActivityConditionInfo().getRewardStr();
        Property property = PropertyHelper.parseStringToProperty(reward);
        int patronId = config.getPatronId();
        if (property.getGoods().containsKey(patronId)) {
            if (gamePlayer.getModule(PatronsModule.class).getUserPatrons(patronId) != null) {
                property.removeProperty(patronId);
                String patronTransToItem = config.getPatronTransToItem();
                Property transTo = PropertyHelper.parseStringToProperty(patronTransToItem);

                String activityName = ServerLanguageMgr.getContent(config.getActivityInfo().getActivityName(), gamePlayer.getLanguage());
                String mailTitle = MultipleLanguageMgr.getContent("GOODS_AUTO_CONSUME_TITLE", gamePlayer.getLanguage());

                String goodsName = "";
                int goodNum = 0;
                for (Map.Entry<Integer, BigInteger> good : transTo.getGoods().entrySet()) {
                    GoodsInfo goodsInfo = GoodsMgr.getGoodsById(good.getKey());

                    if (goodsInfo != null) {
                        goodsName = goodsInfo.getGoodsName();
                        goodsName = MultipleLanguageMgr.getContent(goodsName, gamePlayer.getLanguage());
                    } else {
                        goodsName = MultipleLanguageMgr.getContent("Items-" + good.getKey(), gamePlayer.getLanguage());
                    }
                    goodNum = good.getValue().intValue();

                }
                String patronsName = MultipleLanguageMgr.getContent("Patrons-" + config.getPatronId(), gamePlayer.getLanguage());

                String mailContent = StringUtils.format(MultipleLanguageMgr.getContent("GOODS_AUTO_CONSUME_CONTENT", gamePlayer.getLanguage()), activityName, patronsName, goodsName, goodNum);

                MailManager.sendMail(gamePlayer.getUserId(), eMailType.SYSTEM.getValue(), patronTransToItem, mailContent, mailTitle);
            }
        }
        ;
        activityCondition.setGetReward(true);
        activityCondition.removeTrigger(gamePlayer);
        gamePlayer.getModule(CurrencyModule.class).addCurrency(property, eLogMoneyType.SpecialTombRobSign, eLogMoneyType.SpecialTombRobSignSignReward);
        return PropertyHelper.parsePropertyToString(property);
    }
}
